package com.miyake.loveviewweb.client.viewer;

import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.miyake.loveviewweb.client.viewer.PluginDialogFactory.AnalyzerHandler;
import com.miyake.loveviewweb.client.viewer.PluginDialogFactory.ParserHandler;
import com.miyake.loveviewweb.shared.model.DataModel;
import com.miyake.loveviewweb.shared.model.ValueModel;

public abstract class PluginBar extends Composite {

    abstract void onParse(Key key);
    abstract void onAnalyze(Key key, List<ValueModel> values, Map<String, String> data);
    
    public PluginBar(final DataModel dataModel) {
        HorizontalPanel panel = new HorizontalPanel();
        initWidget(panel);
        
        Button button = new Button();
        button.setText("Analyze");
        button.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                showProcessDialog(dataModel);
            }
            
        });
        panel.add(button);

        if (isParseable(dataModel)) {
            Button parseButton = new Button("Parse File");
            panel.add(parseButton);
            parseButton.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    showParseDialog(dataModel);
                }
            });
            
            if (dataModel.isParsed()) {
                button.setEnabled(true);
            }
            else {
                button.setEnabled(false);
            }
        }
    }
    private boolean isParseable(DataModel dataModel) {
        return dataModel.getSourceType().equals(DataModel.SourceType.File) && dataModel.getDataType().equals(DataModel.DataType.ValueArray);
    }
    
    protected void showProcessDialog(DataModel dataModel) {
        PluginDialogFactory.getInstance().createAnalyzer(new AnalyzerHandler() {
            public void onSelect(Key pluginKey, List<ValueModel> values,
                    Map<String, String> data) {
                
                onAnalyze(pluginKey, values, data);
            }
        }, dataModel);
    }

    protected void showParseDialog(DataModel dataModel) {
        PluginDialogFactory.getInstance().createFileParser(new ParserHandler() {

            public void onSelect(Key pluginKey) {
                onParse(pluginKey);
            }
            
        }, dataModel);
    }
}
